package com.css.resoft.p2pmonitor.dao;

import java.nio.ByteBuffer;
import java.util.List;

import org.apache.hadoop.hbase.thrift2.generated.THBaseService;
import org.apache.hadoop.hbase.thrift2.generated.TPut;
import org.apache.hadoop.hbase.thrift2.generated.TResult;
import org.apache.hadoop.hbase.thrift2.generated.TScan;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;


public class TConnect {
	
	private  TTransport transport = null;
	private  THBaseService.Iface client = null;
	
	public TConnect(String host,int port){
		transport = new TSocket(host,port);
		TProtocol protocol = new TBinaryProtocol(transport);
		client = new THBaseService.Client(protocol);
	}
	
	public boolean putData(ByteBuffer table,TPut put){
		try {
			transport.open();
			client.put(table, put);
		} catch (TException e) {
			e.printStackTrace();
			transport.close();
			return false;
		}
		return true;
	}
	
	public boolean putDatas(ByteBuffer table, List<TPut> puts){
		
		try {
			transport.open();
			client.putMultiple(table, puts);
		} catch (Exception e) {
			e.printStackTrace();
			transport.close();
			return false;
		}
		return true;
	}
	
	public List<TResult> getRecords(long startTs,String isDone,ByteBuffer table){
		
		List<TResult> results = null;
		
//		byte []startRow = Bytes.toBytes(startTs);
		TScan scan = new TScan();
//		scan.setStartRow(startRow);
//		String filter = "(ColumnPrefixFilter('ISDONE') AND ValueFilter(=,'substring:NO'))"
//				+ "OR ColumnPrefixFilter('DATE_STRINGS') ";
		String filter = "(ColumnPrefixFilter('ISDONE') AND ValueFilter(=,'substring:NO'))"
				+ "OR ColumnPrefixFilter('DATE_STRINGS') ";
		
		scan.setFilterString(filter.getBytes());
		
		try {
			transport.open();
			results = client.getScannerResults(table, scan,200);
		} catch (TException e) {
			e.printStackTrace();
		}
		
		return results;
	}
	
	
	public void close(){
		transport.close();
	}
}
